package com.hxf.web.action.order;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.hxf.common.PublicUtil;
import com.hxf.dto.MealBoxDto;
import com.hxf.dto.MealMenuDto;
import com.hxf.dto.MealOrderDetailDto;
import com.hxf.dto.MealOrderDto;
import com.hxf.dto.MealPreferentialDto;
import com.hxf.dto.RestaurantDto;
import com.hxf.dto.ReturnData;
import com.hxf.exception.ServiceException;
import com.hxf.web.action.WebActionBase;
import com.hxf.web.vo.OrderDetailVo;

/**
 * 订单管理Action
 * @author tengyicheng
 * @version [1.0, 2013/11/21]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Results({@Result(name = "success", location = "../common/success.jsp"), @Result(name = "error", location = "../common/error.jsp"), @Result(name = "msg", location = "../common/msg.jsp")})
public class OrderAction extends WebActionBase { 

	private static final long serialVersionUID = 1L;
	private List<MealMenuDto> leftList;
	private List<MealMenuDto> rightList; 
	
	private List<MealBoxDto> boxList; 
	private List<MealOrderDto> orderList;
	private List<MealOrderDetailDto> orderDetailList;
	
	private List<MealPreferentialDto> leftPreferentialList;
	private List<MealPreferentialDto> rightPreferentialList; 
	
	private List<OrderDetailVo> orderVoList;
	
	private MealBoxDto boxDto;
	private MealOrderDto orderDto;
	private String orderId;
	private String name;
	private String contact;
	private String repastDate;
	private Integer peopleNum;
	private Integer boxId; 
	private Integer status;
	
	/**
	 * 餐厅订单列表
	 * @return
	 */
	public String orderList() {
		MealOrderDto mod = new MealOrderDto();
		 try {
			// RestaurantDto dto = new RestaurantDto();
			// List<RestaurantDto> list = getListRestaurantOrAdminDto();
			// if(list.size() > 0){
			//	 dto = list.get(0);
			// }
			 
			 if(PublicUtil.isNotNullAndEmpty(contact)){
				 mod.setContact(contact);
			 }
			 
			 if(PublicUtil.isNotNull(getSession().getAttribute("restaurantId"))){
				 mod.setRestaurantId(Integer.valueOf(getSession().getAttribute("restaurantId").toString()));
			 }
			 ReturnData<MealOrderDto> result = super.serviceFacade.getOrderService().findMealOrder(mod, targetPage, pageSize);
			 orderList = result.getResultlist();
			 this.setRecordCount(result.getRecordcount());
		 } catch (ServiceException e) {
			logger.debug(e.getMessage(), e);
		}
		return "order-list";
	}
	
	/**
	 *  后台管理 -订单管理
	 */
	public String adminOrderList() {
		MealOrderDto mod = new MealOrderDto();
		 try {
			 
			 if(PublicUtil.isNotNullAndEmpty(contact)){
				 mod.setContact(contact);
			 }
			 
			 //mod.setRestaurantId(getRestaurantDto().getId());
			 //mod.setRestaurantId(dto.getId());
			 ReturnData<MealOrderDto> result = super.serviceFacade.getOrderService().findMealOrder(mod, targetPage, pageSize);
			 orderList = result.getResultlist();
			 this.setRecordCount(result.getRecordcount());
		 } catch (ServiceException e) {
			logger.debug(e.getMessage(), e);
		}
		return "order-list";
	}
	
	/**
	 * 订单详细信息
	 * @return
	 */
	public String orderDetail() {
		return "order-detail";
	}
	
	/**
	 * 添加订单页面
	 * @return
	 */
	public String orderAdd() {
		try {
			MealMenuDto mmd = new MealMenuDto();
			RestaurantDto restaurantDto = null;
			List<RestaurantDto> restList = getListRestaurantOrAdminDto();
			if(restList.size() > 0){
				restaurantDto = restList.get(0);
			}
			
			if (restaurantDto != null) {
				//菜肴信息 
				mmd.setRestaurantId(restaurantDto.getId());
				leftList = super.serviceFacade.getMealMenuService().findByMealMenu(mmd);
				orderVoList = new ArrayList<OrderDetailVo>();
				OrderDetailVo detailVo = null;
				for (MealMenuDto menuDto : leftList) {
					detailVo = new OrderDetailVo();
					detailVo.setId(menuDto.getId());
					detailVo.setName(menuDto.getMenuName());
					detailVo.setNum(1);
					detailVo.setType(OrderDetailVo.TYPE_0);
					detailVo.setPrice(menuDto.getPrice());
					orderVoList.add(detailVo);//添加 orderVoList
				} 
				//包厢信息
				MealBoxDto mbd = new MealBoxDto();
				//mbd.setRestaurantId(getRestaurantDto().getId());
				mbd.setRestaurantId(restaurantDto.getId());//餐厅ID
				boxList = super.serviceFacade.getMealBoxService().findByMealBox(mbd);
				//套餐信息
				MealPreferentialDto preferentialDto = new MealPreferentialDto();
				preferentialDto.setRestaurantId(restaurantDto.getId());
				preferentialDto.setPreferentialType(MealPreferentialDto.PREFERENTIAL_TYPE_1);
				//选择优惠套餐 leftPreferentialList
				leftPreferentialList = super.serviceFacade.getPreferentialService().findMealPreferential(preferentialDto);//左边
				for (MealPreferentialDto pDto : leftPreferentialList) {
					detailVo = new OrderDetailVo();
					detailVo.setId(pDto.getId());
					detailVo.setName(pDto.getName());
					detailVo.setNum(1);
					detailVo.setType(OrderDetailVo.TYPE_1);//套餐
					detailVo.setPrice(pDto.getCostPrice());
					detailVo.setPreferentialPrice(pDto.getPreferentialPrice());
					detailVo.setDiscont(pDto.getDiscount());
					orderVoList.add(detailVo);
				}
			} else {
				leftList = new ArrayList<MealMenuDto>();
				leftPreferentialList = new ArrayList<MealPreferentialDto>();
			}  
			rightList = new ArrayList<MealMenuDto>();
			rightPreferentialList = new ArrayList<MealPreferentialDto>(); 
		} catch (ServiceException e) { 
			logger.debug(e.getMessage(), e);
		}
		
		return "order-add-or-update";
	}
	
	/**
	 * 修改订单页面
	 * @return
	 */
	public String orderUpdate() {
		try {
			
			RestaurantDto restaurantDto = null;
			List<RestaurantDto> restList = getListRestaurantOrAdminDto();
			if(restList.size() > 0){
				restaurantDto = restList.get(0);
			}
			
			if (restaurantDto != null) {
				orderDto = (MealOrderDto)super.serviceFacade.getOrderService().get(MealOrderDto.class, orderId);
				if (orderDto != null) {
					//根据订单ID 查询订单相信信息
					MealOrderDetailDto modd = new MealOrderDetailDto();
					modd.setOrderId(orderDto.getOrderId());
					List<MealOrderDetailDto> orderDetailList =  super.serviceFacade.getOrderService().findMealOrderDetail(modd);
					
					MealOrderDetailDto orderDetailDto = null;
					MealMenuDto menuDto = null;
					boolean addBool = true;
					//查询菜肴信息
					MealMenuDto mmd = new MealMenuDto(); 
					mmd.setRestaurantId(restaurantDto.getId());
					List<MealMenuDto> mealMenuList = super.serviceFacade.getMealMenuService().findByMealMenu(mmd);
					//左边菜肴信息 (在页面只有ID和菜肴名称)
					leftList = new ArrayList<MealMenuDto>();
					//右边菜肴信息 (在页面只有ID和菜肴名称)
					rightList = new ArrayList<MealMenuDto>(); 
					//所有菜肴信息
					orderVoList = new ArrayList<OrderDetailVo>();
					OrderDetailVo detailVo = null; 
					
					for (int i = 0;i < mealMenuList.size(); i++) { 
						
						addBool = true;
						menuDto = mealMenuList.get(i);
						detailVo = new OrderDetailVo();
						for (int j = 0;j < orderDetailList.size(); j++) { //菜单
							
							orderDetailDto = orderDetailList.get(j);
							if (orderDetailDto.getMealMenuId() == menuDto.getId() ) {  //&& orderDetailDto.getDetailType() == OrderDetailVo.TYPE_0
								rightList.add(menuDto);
								detailVo.setNum(orderDetailDto.getQuantity());
								addBool = false;
							}
						}
						if (addBool) {
							leftList.add(menuDto);
						}
						
						detailVo.setId(menuDto.getId());
						detailVo.setName(menuDto.getMenuName());
						
						detailVo.setType(OrderDetailVo.TYPE_0);
						detailVo.setPrice(menuDto.getPrice());
						orderVoList.add(detailVo);
					}
					
					//包厢信息
					MealBoxDto mbd = new MealBoxDto();
					//mbd.setRestaurantId(getRestaurantDto().getId());
					mbd.setRestaurantId(restaurantDto.getId());
					boxList = super.serviceFacade.getMealBoxService().findByMealBox(mbd);
					
					//套餐信息
					MealPreferentialDto preferentialDto = new MealPreferentialDto();
					preferentialDto.setRestaurantId(restaurantDto.getId());
					preferentialDto.setPreferentialType(MealPreferentialDto.PREFERENTIAL_TYPE_1);
					List<MealPreferentialDto> preferentialList = super.serviceFacade.getPreferentialService().findMealPreferential(preferentialDto);
					leftPreferentialList = new ArrayList<MealPreferentialDto>();//左边
					rightPreferentialList = new ArrayList<MealPreferentialDto>();//右边
					MealPreferentialDto mpDto = null;
					for (int i = 0;i < preferentialList.size(); i++) {
						addBool = true;
						mpDto = preferentialList.get(i);
						for (int j = 0;j < orderDetailList.size(); j++) {
							orderDetailDto = orderDetailList.get(j);  
							detailVo = new OrderDetailVo();
							
							if (orderDetailDto.getMealMenuId() == mpDto.getId() && orderDetailDto.getDetailType() == OrderDetailVo.TYPE_1) { // 
								rightPreferentialList.add(mpDto);
								detailVo.setNum(orderDetailDto.getQuantity());
								addBool = false;
							}
						}
						if (addBool) {
							leftPreferentialList.add(mpDto);
						}
						detailVo.setId(mpDto.getId());
						detailVo.setName(mpDto.getName()); 
						detailVo.setType(OrderDetailVo.TYPE_1);//类型
						detailVo.setPrice(mpDto.getCostPrice());
						detailVo.setPreferentialPrice(mpDto.getPreferentialPrice());
						detailVo.setDiscont(mpDto.getDiscount());
						orderVoList.add(detailVo);//套餐优惠填充到 orderVoList
					}
				}
			} else {
				leftList = new ArrayList<MealMenuDto>();
				leftPreferentialList = new ArrayList<MealPreferentialDto>(); 
				rightList = new ArrayList<MealMenuDto>();
				rightPreferentialList = new ArrayList<MealPreferentialDto>();
			}   
		} catch (ServiceException e) { 
			logger.debug(e.getMessage(), e);
		}
		return "order-add-or-update"; 
	}
	
	/**
	 * 保持或者修改
	 * @return
	 */
	public String orderSaveOrUpdate() { 
		//RestaurantDto rd = getRestaurantDto();
		RestaurantDto rd = null;
		List<RestaurantDto> restList = getListRestaurantOrAdminDto();
		if(restList.size() > 0){
			rd = restList.get(0);
		}
		
		//MealOrderDto mealOrderDto = new MealOrderDto(orderId, name, contact, repastDate, peopleNum, boxId, 1, rd.getId(), 0);
		MealOrderDto mealOrderDto = new MealOrderDto();
		
		mealOrderDto.setOrderId(orderId);
		mealOrderDto.setName(name);
		mealOrderDto.setContact(contact);
		mealOrderDto.setRepastDate(repastDate);
		mealOrderDto.setPeopleNum(peopleNum);
		if(PublicUtil.isNotNull(boxId)){
			mealOrderDto.setBoxId(boxId);
		}
		
		mealOrderDto.setSendSms(MealOrderDto.SEND_SMS);// 等于1
		if(null != rd){
			mealOrderDto.setRestaurantId(rd.getId());//餐厅编号
		}
		
		mealOrderDto.setStatus(MealOrderDto.STATUS_VALUE);// 状态
		
		if (rd != null) {
			
			try { 
					List<OrderDetailVo> detailVoList = null;
					Object obj = getSession().getAttribute("orderDetailMealMenuList");
					Object obj2 = getSession().getAttribute("orderDetailPreferentialList");
					List<OrderDetailVo> orderDetailList = new ArrayList<OrderDetailVo>();
					
					if (obj != null) {
						detailVoList = (List<OrderDetailVo>)obj; 
						for (OrderDetailVo odv : detailVoList) {
							orderDetailList.add(odv);
						} 
					} 
					if (obj2 != null) {
						detailVoList = (List<OrderDetailVo>)obj2; 
						for (OrderDetailVo odv : detailVoList) {
							orderDetailList.add(odv);
						}
					}
				if (PublicUtil.isNotNullAndEmpty(orderId)) {
					super.serviceFacade.getOrderService().updateOrder(mealOrderDto, orderDetailList);
				} else {
			
					mealOrderDto.setOrderId(String.valueOf(System.currentTimeMillis()));
					super.serviceFacade.getOrderService().saveOrder(mealOrderDto, orderDetailList);
				}
			} catch (ServiceException e) { 
				logger.debug(e.getMessage(), e);
			}
		}
		requestURL = "order!orderList.html";
		
		return SUCCESS;
	}
	
	/**
	 * 记录菜肴详细订单到session
	 * @return
	 */
	public String orderDetailMealMenuAdd() {
		try {
			String orderDetailInfo = getParameter("orderDetailInfo");
			List<OrderDetailVo> detailVoList = new ArrayList<OrderDetailVo>();
			OrderDetailVo detailVo = null;
			if (PublicUtil.isNotNullAndEmpty(orderDetailInfo)) { 
				String orderDetail [] =orderDetailInfo.split(",");
				if (orderDetail != null) {
					for (int i = 0;i < orderDetail.length; i++) { 
						String detailInfo [] = orderDetail[i].split("-");
						if (detailInfo != null && detailInfo.length >= 2) {
							detailVo = new OrderDetailVo();
							detailVo.setId(Integer.parseInt(detailInfo[0]));
							detailVo.setName(detailInfo[1]);
							detailVo.setPrice(Double.parseDouble(detailInfo[2])); 
							detailVo.setNum(Integer.parseInt(detailInfo[3]));
							detailVo.setType(OrderDetailVo.TYPE_0);
							detailVoList.add(detailVo);
						}
					}
				}  
				getSession().setAttribute("orderDetailMealMenuList", detailVoList);
				println(0);
			} else {
				println(-1);
			}
		} catch (IOException e) {
			logger.debug("记录详细订单异常" + e.getMessage(), e);
			e.printStackTrace();
			
		}
		return null;
	} 
	
	/**
	 * 添加套餐详细订单到session
	 * @return
	 */
	public String orderDetailPreferentialAdd() {
		try {
			String orderDetailInfo = getParameter("orderDetailInfo");
			List<OrderDetailVo> detailVoList = new ArrayList<OrderDetailVo>();
			OrderDetailVo detailVo = null;
			if (PublicUtil.isNotNullAndEmpty(orderDetailInfo)) { 
				String orderDetail [] =orderDetailInfo.split(",");
				if (orderDetail != null) {
					for (int i = 0;i < orderDetail.length; i++) { 
						String detailInfo [] = orderDetail[i].split("-");
						if (detailInfo != null && detailInfo.length >= 2) {
							detailVo = new OrderDetailVo();
							detailVo.setId(Integer.parseInt(detailInfo[0]));
							detailVo.setName(detailInfo[1]);
							System.out.println("detailInfo"+detailInfo[2]);
							detailVo.setPrice(Double.parseDouble(detailInfo[2]));
							
							//detailVo.setNum(Integer.parseInt(detailInfo[3]));//结算价格
							detailVo.setType(OrderDetailVo.TYPE_1);
							detailVoList.add(detailVo);
						}
					}
				}  
				getSession().setAttribute("orderDetailPreferentialList", detailVoList);
				println(0);
			} else {
				println(-1);//出错
			}
		} catch (Exception e) {
			logger.debug("记录详细订单异常" + e.getMessage(), e);
			e.printStackTrace();
			
		}
		return null;
	} 
	
	/**
	 * 修改菜肴点菜数量
	 * @return
	 */
	public String updateOrderDetailMealMenuPrice() {
		Object obj = getSession().getAttribute("orderDetailMealMenuList");
		String mId = getParameter("mealMenuId");
		String num = getParameter("num");
		try {
			Integer id = 0;
			Integer number = 1;
			if (PublicUtil.isNotNullAndEmpty(mId)) {
				id = Integer.parseInt(mId);
			}
			
			if (PublicUtil.isNotNullAndEmpty(num)) {
				number = Integer.parseInt(num);
			}
			List<OrderDetailVo> detailVoList = null;
			if (obj != null) {
				 detailVoList = (List<OrderDetailVo>)obj;
			
				 for (int i = 0;i < detailVoList.size(); i++) { 
					 if (id == detailVoList.get(i).getId()) { 
						 detailVoList.get(i).setNum(number);
					 }
				 } 
			} else { 
				println(-1);
			} 
			getSession().setAttribute("orderDetailMealMenuList", detailVoList);
		} catch (IOException e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 修改套餐点菜数量
	 * @return
	 */
	public String updateOrderDetailPreferentialPrice() {
		Object obj = getSession().getAttribute("orderDetailPreferentialList");
		String mId = getParameter("mealMenuId");
		String num = getParameter("num");
		try {
			Integer id = 0;
			Integer number = 1;
			if (PublicUtil.isNotNullAndEmpty(mId)) {
				id = Integer.parseInt(mId);
			}
			
			if (PublicUtil.isNotNullAndEmpty(num)) {
				number = Integer.parseInt(num);
			}
			List<OrderDetailVo> detailVoList = null;
			if (obj != null) {
				 detailVoList = (List<OrderDetailVo>)obj;
			
				 for (int i = 0;i < detailVoList.size(); i++) { 
					 if (id == detailVoList.get(i).getId()) { 
						 detailVoList.get(i).setNum(number);
						 detailVoList.get(i).setPrice(number*detailVoList.get(i).getPrice());
					 }
				 } 
			} else { 
				println(-1);
			} 
			getSession().setAttribute("orderDetailPreferentialList", detailVoList);
		} catch (IOException e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	public String orderQuery() { 
		try {
			//RestaurantDto restaurantDto = getRestaurantDto();
			RestaurantDto restaurantDto = null;
			
			List<RestaurantDto> restList = getListRestaurantOrAdminDto();
			if(restList.size() > 0){
				restaurantDto = restList.get(0);
			}
			
			if (restaurantDto != null) {
				orderDto = (MealOrderDto)super.serviceFacade.getOrderService().get(MealOrderDto.class, orderId);
				if (orderDto != null) {
					//查询包厢信息
					boxDto = (MealBoxDto)super.serviceFacade.getMealBoxService().get(MealBoxDto.class, orderDto.getBoxId());
					
					//根据订单ID 查询订单相信信息
					MealOrderDetailDto modd = new MealOrderDetailDto();
					modd.setOrderId(orderDto.getOrderId());
					orderDetailList =  super.serviceFacade.getOrderService().findMealOrderDetail(modd);
				}
			}
		} catch (ServiceException e) {
			logger.debug(e.getMessage(), e);
		}
		return "order-query";
	}
	
	/**
	 * 删除订单
	 * @return
	 * @throws ServiceException 
	 * @throws IOException 
	 */
	public String orderDelete() throws ServiceException, IOException {
		System.out.println("orderId:"+orderId);
		String data = "";
		// 删除订单表主表数据
		if(PublicUtil.isNotNullAndEmpty(orderId)){
			super.serviceFacade.getOrderService().deleteMealOrderBy(orderId);//主表中数据
			super.serviceFacade.getOrderService().deteleMealOrderDetailByOrderId(orderId);//订单详细
			data = "success";
		}
		println(data);	
		return null;
	}

	public List<MealOrderDto> getOrderList() {
		return orderList;
	}

	public void setOrderList(List<MealOrderDto> orderList) {
		this.orderList = orderList;
	} 

	public List<MealMenuDto> getLeftList() {
		return leftList;
	}

	public void setLeftList(List<MealMenuDto> leftList) {
		this.leftList = leftList;
	}

	public List<MealMenuDto> getRightList() {
		return rightList;
	}

	public void setRightList(List<MealMenuDto> rightList) {
		this.rightList = rightList;
	}

	public List<MealBoxDto> getBoxList() {
		return boxList;
	}

	public void setBoxList(List<MealBoxDto> boxList) {
		this.boxList = boxList;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRepastDate() {
		return repastDate;
	}

	public void setRepastDate(String repastDate) {
		this.repastDate = repastDate;
	}

	public Integer getPeopleNum() {
		return peopleNum;
	}

	public void setPeopleNum(Integer peopleNum) {
		this.peopleNum = peopleNum;
	}

	public Integer getBoxId() {
		return boxId;
	}

	public void setBoxId(Integer boxId) {
		this.boxId = boxId;
	}

	public String getContact() {
		return contact;
	}

	public void setContact(String contact) {
		this.contact = contact;
	}

	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

	public List<MealPreferentialDto> getLeftPreferentialList() {
		return leftPreferentialList;
	}

	public void setLeftPreferentialList(
			List<MealPreferentialDto> leftPreferentialList) {
		this.leftPreferentialList = leftPreferentialList;
	}

	public List<MealPreferentialDto> getRightPreferentialList() {
		return rightPreferentialList;
	}

	public void setRightPreferentialList(
			List<MealPreferentialDto> rightPreferentialList) {
		this.rightPreferentialList = rightPreferentialList;
	}

	public MealOrderDto getOrderDto() {
		return orderDto;
	}

	public void setOrderDto(MealOrderDto orderDto) {
		this.orderDto = orderDto;
	}

	public List<OrderDetailVo> getOrderVoList() {
		return orderVoList;
	}

	public void setOrderVoList(List<OrderDetailVo> orderVoList) {
		this.orderVoList = orderVoList;
	}

	public List<MealOrderDetailDto> getOrderDetailList() {
		return orderDetailList;
	}

	public void setOrderDetailList(List<MealOrderDetailDto> orderDetailList) {
		this.orderDetailList = orderDetailList;
	}

	public MealBoxDto getBoxDto() {
		return boxDto;
	}

	public void setBoxDto(MealBoxDto boxDto) {
		this.boxDto = boxDto;
	}
}
